package demo.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.List;

/**
 * @author lingyun.wang on @date 2021/11/24
 */
public class JsonReadUtils {
    private static Logger log = LoggerFactory.getLogger(JsonReadUtils.class);
    private static JsonReadUtils jsonReadUtils = new JsonReadUtils();
    private JsonReadUtils(){}
    public static JSONObject readObject(String filePath){
        String jsonStr = jsonReadUtils.readFileToStr(filePath);
        if(!jsonStr.startsWith("{")){
            log.error("json str not startsWith {");
            return null;
        }
        return JSONObject.parseObject(jsonStr);
    }

    public static JSONArray readArray(String filePath){
        String jsonStr = jsonReadUtils.readFileToStr(filePath);
        if(!jsonStr.startsWith("[")){
            log.error("json str not startsWith [");
            return null;
        }
        return JSONArray.parseArray(jsonStr);
    }

    public static <T> List<T> readArray(String filePath,Class<T> clazz){
        String jsonStr = jsonReadUtils.readFileToStr(filePath);
        if(!jsonStr.startsWith("[")){
            log.error("json str not startsWith [");
            return null;
        }
        return JSONArray.parseArray(jsonStr,clazz);
    }

    public static <T> T readObject(String filePath,Class<T> clazz){
        String jsonStr = jsonReadUtils.readFileToStr(filePath);
        if(!jsonStr.startsWith("{")){
            log.error("json str not startsWith {");
            return null;
        }
        return JSONObject.parseObject(jsonStr,clazz);
    }


    private String readFileToStr(String filePath) {
        filePath = "data/"+filePath;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
        if(null==inputStream){
            return "";
        }
        BufferedReader reader = null;
        try {
            InputStreamReader streamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(streamReader);
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            log.error("error read rule file!",e);
        }finally {
            try {
                if (reader != null){ reader.close();}
                if (inputStream != null){ inputStream.close();}
            } catch (IOException y) {
                log.error("error closing rule file!",y);
            }
        }
        return "";
    }
}
